import 'package:enjoy_plus/models/mine_nav_model.dart';
import 'package:enjoy_plus/models/user_info_model.dart';
import 'package:enjoy_plus/pages/login/login.dart';
import 'package:enjoy_plus/pages/mine/user_info.dart';
import 'package:enjoy_plus/utils/eventbus.dart';
import 'package:enjoy_plus/utils/http.dart';
import 'package:enjoy_plus/utils/logger.dart';
import 'package:enjoy_plus/utils/toast.dart';
import 'package:enjoy_plus/utils/token.dart';
import 'package:flutter/material.dart';
// 引入苹果风格组件
import 'package:flutter/cupertino.dart';

class MinePage extends StatefulWidget {
  MinePage({super.key, required this.currentIndex});

  final int currentIndex;
  //数据
  final List<MineItem> mineList = [
    MineItem(
        title: '我的房屋',
        icon: 'assets/images/house_profile_icon@2x.png',
        route: '/house'),
    MineItem(
        title: '我的报修',
        icon: 'assets/images/repair_profile_icon@2x.png',
        route: '/repair'),
    MineItem(
        title: '访客记录',
        icon: 'assets/images/visitor_profile_icon@2x.png',
        route: '/visitor')
  ];

  @override
  State<MinePage> createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  late final TokenManager tokenManager;
  String token = '';
  bool airplaneMode = false;

  @override
  void initState() {
    super.initState();
    tokenManager = TokenManager();
    // ToastUtil.showSuccess('token: $token');
    eventBus.on<RefreshMine>().listen((event) {
      getProfile();
    });
    eventBus.on<BackMine>().listen((event) {
      ToastUtil.showSuccess('666');
      getProfile();
    });
  }

  UserInfoModel userInfo = UserInfoModel(id: '', avatar: '', nickName: '');

  getProfile() async {
    try {
      var res = await http.get<UserInfoModel>('/userInfo',
          fromJson: (json) => UserInfoModel.fromJson(json));
      if (res.code != 10000) return ToastUtil.showError('获取数据失败');
      setState(() {
        userInfo = res.data;
        ToastUtil.showSuccess('${userInfo.nickName}');
        token = tokenManager.getToken() ?? '';
      });
    } catch (e) {
      ToastUtil.showError('获取数据失败${e.toString()}');
      logger.e(e);
    }
  }

  @override
  void didUpdateWidget(covariant MinePage oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.currentIndex == 1) {
      getProfile();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color.fromARGB(200, 85, 145, 175),
      appBar: AppBar(
          title: const Text(
            '我的',
            style: TextStyle(color: Colors.white),
          ),
          backgroundColor: Colors.transparent,
          centerTitle: true),
      body: Container(
        padding: const EdgeInsets.all(10),
        child: Column(
          children: [
            Row(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(50),
                  child: userInfo.avatar?.isNotEmpty == true
                      ? Image.network(userInfo.avatar!,
                          width: 50, height: 50, fit: BoxFit.cover)
                      : Image.asset(
                          'assets/images/avatar_1.jpg',
                          width: 50,
                          height: 50,
                          fit: BoxFit.cover,
                        ),
                ),
                Expanded(
                  child: Container(
                    margin: const EdgeInsets.only(left: 10),
                    child: GestureDetector(
                      onTap: () {
                        Navigator.push(context,
                            MaterialPageRoute(builder: (context) => Login()));
                      },
                      child: Text(
                        token.isEmpty ? '未登录' : userInfo.nickName ?? '无昵称',
                        style: const TextStyle(color: Colors.white),
                        overflow: TextOverflow.ellipsis,
                        maxLines: 2,
                      ),
                    ),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => UserInfo(userInfo: userInfo)),
                    );
                  },
                  child: Text(
                    token.isEmpty ? '去登录' : '去完善信息',
                    style: const TextStyle(color: Colors.white),
                  ),
                ),
                const Icon(Icons.chevron_right, color: Colors.white)
              ],
            ),
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(10),
              margin: const EdgeInsets.only(top: 20),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(10),
              ),
              child: Column(
                children: [
                  ...widget.mineList.map((item) => MineItemWidget(item)),
                  Row(
                    children: [
                      Container(
                        width: 100,
                        height: 40,
                        decoration: BoxDecoration(
                          color: Colors.blue,
                          borderRadius: BorderRadius.circular(10),
                        ),
                        child: CupertinoButton(
                            color: Colors.blue,
                            padding: const EdgeInsets.all(0),
                            onPressed: () {
                              tokenManager.saveToken('我是token114514');
                            },
                            child: const Text('存储token',
                                style: TextStyle(color: Colors.white,fontSize: 15))),
                      ),
                      const SizedBox(width: 10),
                      Container(
                        width: 100,
                        height: 40,
                        child: CupertinoButton(
                            color: Colors.blue,
                            padding: const EdgeInsets.all(0),
                            onPressed: () {
                              tokenManager.removeToken();
                            },
                            child: const Text('删除token',
                                style: TextStyle(
                                    color: Colors.white, fontSize: 15))),
                      ),
                      const SizedBox(width: 10),
                      Container(
                        width: 100,
                        height: 40,
                        child: CupertinoButton(
                            color: Colors.blue,
                            padding: const EdgeInsets.all(0),
                            onPressed: () {
                              logger.d('token: ${tokenManager.getToken()}');
                            },
                            child: const Text('获取token',
                                style: TextStyle(
                                    color: Colors.white, fontSize: 15))),
                      ),
                    ],
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}

class MineItemWidget extends StatelessWidget {
  final MineItem item;
  const MineItemWidget(this.item, {super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(top: 10, bottom: 10),
      child: Row(
        children: [
          Image.asset(item.icon, width: 24, height: 24),
          const SizedBox(width: 10),
          Expanded(child: Text(item.title)),
          const Icon(Icons.chevron_right, color: Colors.grey)
        ],
      ),
    );
  }
}

class PrefixWidget extends StatelessWidget {
  const PrefixWidget({
    super.key,
    required this.icon,
    required this.title,
    required this.color,
  });

  final IconData icon;
  final String title;
  final Color color;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        Container(
          padding: const EdgeInsets.all(4.0),
          decoration: BoxDecoration(
            color: color,
            borderRadius: BorderRadius.circular(4.0),
          ),
          child: Icon(icon, color: CupertinoColors.white),
        ),
        const SizedBox(width: 15),
        Text(title)
      ],
    );
  }
}
